package com.wyu.blog.controller;

import com.wyu.blog.dto.AccessTokenParam;
import com.wyu.blog.dto.GitHubUser;
import com.wyu.blog.entity.User;
import com.wyu.blog.service.UserService;
import com.wyu.blog.util.CustomizeErrorCode;
import com.wyu.blog.util.CustomizeException;
import com.wyu.blog.util.GitHubProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Controller
public class AuthorizationController {

    @Autowired
    GitHubProvider gitHubProvider;

    @Autowired
    UserService userService;


    @Value("${github.client.id}")
    private String client_id;
    @Value("${github.client.secret}")
    private String client_secret;
    @Value("${github.redirect.uri}")
    private String redirect_uri;

    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                           HttpServletResponse response, HttpSession session){

        AccessTokenParam accessTokenParam = new AccessTokenParam();
        accessTokenParam.setCode(code);
        accessTokenParam.setState(state);
        accessTokenParam.setClient_id(client_id);
        accessTokenParam.setClient_secret(client_secret);
        accessTokenParam.setRedirect_uri(redirect_uri);

        String Token = gitHubProvider.getAccessToken(accessTokenParam);   //获取到access_token

        String accessToken = Token.split("&")[0].split("=")[1];
        //使用access_token获取github用户信息
        GitHubUser gitHubUser = gitHubProvider.getGitHubUser(accessToken);
//        System.out.println(gitHubUser.toString());
        if(gitHubUser != null){
//            String token = userService.createOrUpdateUser(gitHubUser);
            User user = userService.createOrUpdateUser(gitHubUser);
//            Cookie cookie = new Cookie("token", token);
//            //设置cookie生命周期
//            cookie.setMaxAge(60 * 60 * 24 * 30 * 6);
//            response.addCookie(cookie);
            session.setAttribute("loginUser", user);

//            User user = new User();
//            String str = UUID.randomUUID().toString().substring(0, 6);
            //获得个人github账号的用户名: gitHubUser.getName()
//            if(StringUtils.isBlank(gitHubUser.getName())){
//                user.setUserName("GitHub"+gitHubUser.getId());
//            }else{
//                user.setUserName(gitHubUser.getName());
//            }
//
//            user.setUserSalt(UUID.randomUUID().toString().substring(0, 5));
//            user.setUserPassword(BlogUtil.MD5(str + user.getUserSalt()));
//            user.setUserRegistrationTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//            User user1 = userService.findUserByName(user.getUserName());
//            if(user1 == null) {
//                userService.addUser(user);
//                session.setAttribute("loginUser", user);
//                return "main";
//            }else{
//                return "main";
//            }
        }else{
            throw new CustomizeException(CustomizeErrorCode.GITHUB_AUTH_WRONG);
        }
        return "redirect:/main";
    }
}